<!--
 * @Description: 
 * @Author: xunzhaotech
 * @Email: luyb@xunzhaotech.com
 * @QQ: 1525572900
 * @Date: 2025-03-23 18:54:49
 * @LastEditTime: 2025-03-23 18:55:15
 * @LastEditors: xunzhaotech
-->
<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
    :disabled="disabled"
  >
    <el-table :data="formData" show-summary :summary-method="getSummaries" class="-mt-10px">
      <el-table-column label="序号" type="index" align="center" width="60" />
      <!-- <el-table-column label="仓库名称" min-width="125">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.warehouseId`"
            :rules="formRules.warehouseId"
            class="mb-0px!"
          >
            <el-select
              v-model="row.warehouseId"
              clearable
              filterable
              placeholder="请选择仓库"
              @change="onChangeWarehouse($event, row)"
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column> -->
      <el-table-column label="产品名称" min-width="180">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productId`" :rules="formRules.productId" class="mb-0px!">
            <el-select
              v-model="row.productId"
              clearable
              filterable
              @change="onChangeProduct($event, row)"
              placeholder="请选择产品"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <!-- <el-table-column label="库存" min-width="100">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.stockCount" :formatter="erpCountInputFormatter" />
          </el-form-item>
        </template>
      </el-table-column> -->
      <el-table-column label="条码" min-width="150">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.barCode" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单位" min-width="80">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.productUnitName" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="数量" prop="count" min-width="140">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.count`" :rules="formRules.count" class="mb-0px!">
            <el-input-number
              v-model="row.count"
              controls-position="right"
              :min="1"
              :precision="0"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <!-- <el-table-column label="产品单价" fixed="right" min-width="120">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productPrice`" class="mb-0px!">
            <el-input-number
              v-model="row.productPrice"
              controls-position="right"
              :min="0.01"
              :precision="2"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="合计金额" prop="totalPrice" fixed="right" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.totalPrice`" class="mb-0px!">
            <el-input disabled v-model="row.totalPrice" :formatter="erpPriceInputFormatter" />
          </el-form-item>
        </template>
      </el-table-column> -->
      <el-table-column label="备注" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`" class="mb-0px!">
            <el-input v-model="row.remark" placeholder="请输入备注" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3" v-if="!disabled">
    <el-button @click="handleAdd" round>+ 添加入库产品</el-button>
  </el-row>
</template>
<script setup lang="ts">
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/warehouse'
import {
  // erpCountInputFormatter,
  erpPriceInputFormatter,
  erpPriceMultiply,
  getSumValue
} from '@/utils'

const props = defineProps<{
  items: never[]
  disabled: boolean
  type?: string
  warehouseId?: number
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref<(ProductVO & { totalPrice?: number; productPrice?: number })[]>([])
const formRules = reactive({
  inId: [{ required: true, message: '入库编号不能为空', trigger: 'blur' }],
  warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '产品不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '产品数量不能为空', trigger: 'blur' }]
})
const formRef = ref([]) // 表单 Ref
const productList = ref<ProductVO[]>([]) // 产品列表
const warehouseList = ref<WarehouseVO[]>([]) // 仓库列表
const defaultWarehouse = ref<WarehouseVO | null>(null) // 默认仓库
/** 初始化设置入库项 */
watch(
  () => props.items,
  async (val) => {
    formData.value = val
  },
  { immediate: true }
)

/** 监听合同产品变化，计算合同产品总价 */
watch(
  () => formData.value,
  (val) => {
    if (!val || val.length === 0) {
      return
    }
    // 循环处理
    val.forEach((item) => {
      // 确保 productPrice 和 count 都有值时才计算总价
      if (item.productPrice && (item as any).count) {
        item.totalPrice = erpPriceMultiply(item.productPrice, (item as any).count)
      }
    })
  },
  { deep: true }
)

/** 合计 */
const getSummaries = (param: any) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (['count', 'totalPrice'].includes(column.property)) {
      const sum = getSumValue(data.map((item) => Number(item[column.property])))
      sums[index] = column.property === 'count' ? String(sum) : erpPriceInputFormatter(sum)
    } else {
      sums[index] = ''
    }
  })

  return sums
}

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: 0, // 修改为数字类型以符合ProductVO接口要求
    inId: undefined, // 入库编号
    warehouseId: props.warehouseId, // 仓库ID,
    warehouseName: undefined,
    type: undefined, // 产品类型
    productId: null, // 符合ProductVO接口要求
    productName: undefined,
    productUnitId: undefined,
    productUnitName: undefined, // 产品单位
    categoryId: 0, // 修改为数字类型以符合ProductVO接口要求
    categoryName: undefined,
    componentsGroup: undefined,
    name: '', // 已符合ProductVO接口要求
    purchasePrice: 0, // 修改为数字类型以符合ProductVO接口要求
    salePrice: 0, // 修改为数字类型以符合ProductVO接口要求
    standard: '', // 修改为字符串类型以符合ProductVO接口要求
    weight: 0, // 修改为数字类型以符合ProductVO接口要求
    status: 0, // 修改为数字类型以符合ProductVO接口要求
    unitId: 0, // 修改为数字类型以符合ProductVO接口要求
    unitName: undefined,
    expiryDay: 0, // 修改为数字类型以符合ProductVO接口要求
    barCode: '', // 修改为字符串类型以符合ProductVO接口要求
    productBarCode: undefined, // 兼容旧字段
    minPrice: 0, // 修改为数字类型以符合ProductVO接口要求
    productPrice: undefined,
    stockCount: undefined, // 库存
    count: 1, // 产品数量
    totalPrice: undefined, // 产品总价
    remark: '' // 修改为字符串类型以符合ProductVO接口要求
  }
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 处理仓库变更 */
// const onChangeWarehouse = (warehouseId, row) => {
//   // 加载库存
//   setStockCount(row)
// }

/** 处理产品变更 */
const onChangeProduct = (productId, row) => {
  const product = productList.value.find((item) => item.id === productId)
  if (product) {
    row.productName = product.name
    row.productUnitId = product.unitId
    row.productUnitName = product.unitName
    row.categoryId = product.categoryId
    row.categoryName = product.categoryName
    row.barCode = product.barCode
    row.productBarCode = product.barCode // 兼容旧字段
    row.productPrice = product.purchasePrice
    // 添加其他字段映射
    row.purchasePrice = product.purchasePrice
    row.salePrice = product.salePrice
    row.standard = product.standard
    row.weight = product.weight
    row.status = product.status
    row.expiryDay = product.expiryDay
    row.componentsGroup = product.componentsGroup
    row.type = product.type
  }
  // 加载库存
  // setStockCount(row)
}

/** 加载库存 */
// const setStockCount = async (row) => {
//   if (!row.productId || !row.warehouseId) {
//     return
//   }
//   // 使用ProductApi替代StockApi，修改API路径从/erp/stock/get到/erp/product/get
//   const stock = await ProductApi.getProduct(row.productId)
//   row.stockCount = stock ? stock.count : 0
// }

/** 表单校验 */
const validate = () => {
  // 由于formRef是数组类型,需要使用类型断言来调用validate方法
  return (formRef.value as any).validate()
}
defineExpose({ validate })

/** 根据类型加载产品列表 */
const loadProductList = async () => {
  if (props.type === 'finished') {
    // 加载成品列表
    productList.value = await ProductApi.getFinishedProductList()
  } else if (props.type === 'components') {
    // 加载零部件列表
    productList.value = await ProductApi.getComponentsProductList()
  } else {
    // 加载所有产品列表
    // productList.value = await ProductApi.getProductList()
  }
}

/** 监听type属性变化 */
watch(
  () => props.type,
  async () => {
    await loadProductList()
  }
)

/** 初始化 */
onMounted(async () => {
  warehouseList.value = await WarehouseApi.getWarehouseSimpleList()
  defaultWarehouse.value = warehouseList.value.find((item) => item.defaultStatus) || null
  // 默认添加一个
  if (formData.value.length === 0) {
    handleAdd()
  }
})
</script>
